package com.cloud.pikachu.storage.service.impl;

import com.cloud.pikachu.storage.api.dto.UploadImageDTO;
import com.cloud.pikachu.storage.api.vo.ExecuteResult;
import com.cloud.pikachu.storage.api.vo.UploadImageVO;
import com.cloud.pikachu.storage.config.LocalOssConfig;
import com.cloud.pikachu.storage.config.LocalOssResponse;
import com.cloud.pikachu.storage.config.OssException;
import com.cloud.pikachu.storage.service.ImageUploadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * 图片上传处理service接口
 *
 * @author : ABug
 * @Date : 2019/4/30 16:04
 * @UpdateDate : 2019/4/30 16:04
 * @Version V1.0.0
 **/
@Slf4j
@Service
public class ImageUploadServiceImpl implements ImageUploadService {

    @Autowired
    private LocalOssConfig localOssConfig;

    @Override
    public ExecuteResult<UploadImageVO> imageUpload(UploadImageDTO uploadImageDTO) {
        ExecuteResult executeResult = new ExecuteResult();

        try {
            switch (uploadImageDTO.getSaveType()){
                case 1 ://阿里云OSS
                    throw new OssException("暂未开通阿里云OSS存储服务");
                case 2 ://腾讯OSS
                    throw new OssException("暂未开通腾讯云OSS存储服务");
                case 3 ://七牛OSS
                    throw new OssException("暂未开通七牛云OSS存储服务");
                case 4 ://本地保存
                    executeResult = saveLocalOss(uploadImageDTO);
                    break;
                case 5 ://FTPOSS
                    throw new OssException("暂未开通FTP存储服务");
                default:
                    throw new OssException("存储类型参数错误");
            }

        } catch (OssException e) {
            log.error(e.getMessage() , e);
            executeResult.setError(999 , e.getMessage());
        } catch (IOException e) {
            log.error(e.getMessage() , e);
            executeResult.setError(999 , "未知异常，"+e.getMessage());
        }

        return executeResult;
    }

    private ExecuteResult<UploadImageVO> saveLocalOss(UploadImageDTO uploadImageDTO) throws IOException, OssException {

        ExecuteResult executeResult = new ExecuteResult();
        UploadImageVO vo = new UploadImageVO();

        LocalOssResponse localOssResponse = localOssConfig.save(uploadImageDTO.getMultipartFile().getInputStream() ,
                uploadImageDTO.getMultipartFile().getOriginalFilename(),
                uploadImageDTO.getSaveDuration() , uploadImageDTO.getZipSize());
        vo.setDiyHreads(localOssResponse.getDiyHreads());
        vo.setFileSize(localOssResponse.getFileSize());
        vo.setFileUrlPath(localOssResponse.getFileUrlPath());
        vo.setSaveDuration(localOssResponse.getSaveDuration());
        vo.setSaveType(localOssResponse.getSaveType());
        executeResult.setResult(vo);

        return executeResult;
    }
}
